package com.demo.practiceui.views.animation;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

/**
 * 波浪动画View
 * 核心知识点：
 * 1. Path.quadTo() - 贝塞尔曲线绘制波浪
 * 2. ValueAnimator - 控制波浪滚动
 * 3. 三角函数 - 生成波浪曲线
 * 4. 多层波浪叠加
 */
public class WaveView extends View {

    // 波浪参数
    private float waveLength = 600f;    // 波长
    private float waveHeight = 100f;     // 波高
    private float waveOffset = 0f;      // 波浪偏移量
    private float waterLevel = 0.6f;    // 水位（0-1）

    // 画笔
    private Paint wavePaint1;           // 第一层波浪
    private Paint wavePaint2;           // 第二层波浪
    private Paint textPaint;            // 文字画笔

    // 尺寸
    private int width;
    private int height;

    // 路径
    private Path wavePath1;
    private Path wavePath2;

    // 动画
    private ValueAnimator waveAnimator;

    public WaveView(Context context) {
        this(context, null);
    }

    public WaveView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WaveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 第一层波浪（深色）
        wavePaint1 = new Paint(Paint.ANTI_ALIAS_FLAG);
        wavePaint1.setColor(Color.parseColor("#802196F3"));
        wavePaint1.setStyle(Paint.Style.FILL);

        // 第二层波浪（浅色）
        wavePaint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
        wavePaint2.setColor(Color.parseColor("#4064B5F6"));
        wavePaint2.setStyle(Paint.Style.FILL);

        // 文字画笔
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(72f);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setFakeBoldText(true);

        wavePath1 = new Path();
        wavePath2 = new Path();

        // 启动波浪动画
        startWaveAnimation();
    }

    /**
     * 启动波浪动画
     */
    private void startWaveAnimation() {
        waveAnimator = ValueAnimator.ofFloat(0, waveLength);
        waveAnimator.setDuration(2000);
        waveAnimator.setRepeatCount(ValueAnimator.INFINITE);
        waveAnimator.setInterpolator(new LinearInterpolator());
        waveAnimator.addUpdateListener(animation -> {
            waveOffset = (float) animation.getAnimatedValue();
            invalidate();
        });
        waveAnimator.start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = 600;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = 400;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 1. 绘制第一层波浪
        drawWave(canvas, wavePath1, wavePaint1, waveOffset, 0);

        // 2. 绘制第二层波浪（偏移半个波长，产生交错效果）
        drawWave(canvas, wavePath2, wavePaint2, waveOffset, waveLength / 2);

        // 3. 绘制水位百分比
        drawWaterLevelText(canvas);
    }

    /**
     * 绘制波浪
     */
    private void drawWave(Canvas canvas, Path path, Paint paint, float offset, float phaseOffset) {
        path.reset();

        // 计算水位线Y坐标
        float waterLineY = height * (1 - waterLevel);

        // 起点：从左边界开始
        path.moveTo(-waveLength + offset-phaseOffset, waterLineY);

        // 使用quadTo绘制贝塞尔曲线模拟波浪
        float x = -waveLength + offset - phaseOffset;
        while (x < width + waveLength) {
            // 波峰
            path.quadTo(
                    x + waveLength / 4, waterLineY - waveHeight,
                    x + waveLength / 2, waterLineY
            );
            // 波谷
            path.quadTo(
                    x + waveLength * 3 / 4, waterLineY + waveHeight,
                    x + waveLength, waterLineY
            );
            x += waveLength;
        }

        // 连接到右下角、左下角，形成封闭区域
        path.lineTo(width, height);
        path.lineTo(0, height);
        path.close();

        canvas.drawPath(path, paint);
    }

    /**
     * 绘制水位文字
     */
    private void drawWaterLevelText(Canvas canvas) {
        float waterLineY = height * (1 - waterLevel);
        String text = String.format("%.0f%%", waterLevel * 100);
        
        // 绘制文字（在水位线附近）
        textPaint.setTextSize(72f);
        canvas.drawText(text, width / 2f, waterLineY - 20, textPaint);

        textPaint.setTextSize(32f);
        canvas.drawText("水位", width / 2f, waterLineY + 30, textPaint);
    }

    /**
     * 设置水位（带动画）
     */
    public void setWaterLevel(float level) {
        ValueAnimator animator = ValueAnimator.ofFloat(waterLevel, level);
        animator.setDuration(1000);
        animator.addUpdateListener(animation -> {
            waterLevel = (float) animation.getAnimatedValue();
            invalidate();
        });
        animator.start();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (waveAnimator != null) {
            waveAnimator.cancel();
        }
    }

    /**
     * 暂停动画
     */
    public void pause() {
        if (waveAnimator != null && waveAnimator.isRunning()) {
            waveAnimator.pause();
        }
    }

    /**
     * 恢复动画
     */
    public void resume() {
        if (waveAnimator != null && waveAnimator.isPaused()) {
            waveAnimator.resume();
        }
    }
}

